import {
  $,
  _,
  UserSelectAutoComplete,
  ActionDialog,
  ConfirmDialog,
  InfoDialog,
  Notification,
  NamedPage,
  delay,
  i18n,
  request,
  tpl,
  addPage,
} from "@hydrooj/ui-default";
const page = new NamedPage("schoolmanage_user", () => {
  const setRolesDialog = new ActionDialog({
    $body: $(".dialog__body--set-role > div"),
    onDispatch(action) {
      const $role = setRolesDialog.$dom.find('[name="role"]');
      if (action === "ok" && !$role.val()) {
        $role.focus();
        return false;
      }
      return true;
    },
  });
  function ensureAndGetSelectedUsers() {
    const users = _.map(
      $('.domain-users tbody [type="checkbox"]:checked'),
      (ch) => $(ch).attr("data-uid") || $(ch).closest("tr").attr("data-uid")
    );
    if (users.length === 0) {
      Notification.error(
        i18n("Please select at least one user to perform this operation.")
      );
      return null;
    }
    return users;
  }
  async function handleClickResetpassSelected() {
    const selectedUsers = ensureAndGetSelectedUsers();
    if (selectedUsers === null) {
      return;
    }
    const action = await new ConfirmDialog({
      $body: tpl`
        <div class="typo">
          <p>${i18n("Confirm reset password the selected users?")}</p>
          <p>${i18n(
            "Their account`s password will be reset  and they will login this site with the new password abc123. Please tell them edit passwod after soon."
          )}</p>
        </div>`,
    }).open();
    if (action !== "yes") return;
    try {
      await request.post("", {
        operation: "resetpass",
        uids: selectedUsers,
      });
      Notification.success(i18n("Selected users have been reset password."));
      await delay(2000);
      window.location.reload();
    } catch (error) {
      Notification.error(error.message);
    }
  }
  async function handleClickSetSelected() {
    const selectedUsers = ensureAndGetSelectedUsers();
    if (selectedUsers === null) {
      return;
    }
    const action = await setRolesDialog.clear().open();
    if (action !== "ok") {
      return;
    }
    const role = setRolesDialog.$dom.find('[name="role"]').val();
    try {
      await request.post("", {
        operation: "set_users",
        uids: selectedUsers,
        role,
      });
      Notification.success(
        i18n("Role has been updated to {0} for selected users.", role)
      );
      await delay(2000);
      window.location.reload();
    } catch (error) {
      Notification.error(error.message);
    }
  }

  async function handleChangeUserRole(ev) {
    const row = $(ev.currentTarget).closest("tr");
    const role = $(ev.currentTarget).val();
    try {
      await request.post("", {
        operation: "set_users",
        uids: [row.attr("data-uid")],
        role,
      });
      Notification.success(i18n("Role has been updated to {0}.", role));
    } catch (error) {
      Notification.error(error.message);
    }
  }
  $('[name="add_user"]').click(() => handleClickAddUser());
  $('[name="resetpass_selected"]').click(() => handleClickResetpassSelected());
  $('[name="set_roles"]').click(() => handleClickSetSelected());
  $('.domain-users [name="role"]').change((ev) => handleChangeUserRole(ev));
});
addPage(page);
